import { Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { config } from '@/config';
import { AuthenticatedRequest, ErrorCode } from '@/types';
import { createApiError } from '@/utils/response';

export const authenticateToken = (
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction
): void => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

  if (!token) {
    const error = createApiError(
      ErrorCode.AUTHENTICATION_ERROR,
      'Access token is required'
    );
    res.status(401).json(error);
    return;
  }

  try {
    const decoded = jwt.verify(token, config.jwt.secret) as any;
    req.user = {
      id: decoded.id,
      email: decoded.email,
      username: decoded.username,
    };
    next();
  } catch (error) {
    const apiError = createApiError(
      ErrorCode.AUTHENTICATION_ERROR,
      'Invalid or expired token'
    );
    res.status(403).json(apiError);
  }
};